package com.L.yygh.order.service.impl;

import com.L.yygh.enums.PaymentStatusEnum;
import com.L.yygh.enums.PaymentTypeEnum;
import com.L.yygh.enums.RefundStatusEnum;
import com.L.yygh.model.order.OrderInfo;
import com.L.yygh.model.order.PaymentInfo;
import com.L.yygh.model.order.RefundInfo;
import com.L.yygh.order.config.HttpClient;
import com.L.yygh.order.config.WeixinPayProperties;
import com.L.yygh.order.service.OrderService;
import com.L.yygh.order.service.RefundService;
import com.L.yygh.order.service.impl.OrderServiceImpl;
import com.L.yygh.order.service.PaymentService;
import com.L.yygh.order.service.WeixinService;
import com.alibaba.fastjson.JSONObject;
import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class WeixinServiceImpl implements WeixinService {

    @Autowired
    private PaymentService paymentService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private WeixinPayProperties weixinPayProperties;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RefundService refundService;

    //生成微信支付二维码
    @Override
    public Map createNative(Long orderId) {

        //从redis获取数据
        Map payMap = (Map) redisTemplate.opsForValue().get(orderId.toString());
        if(payMap != null){
            return payMap;
        }

        //1.根据orderId获取信息
        OrderInfo orderInfo = orderService.getById(orderId);
        //2.向支付记录表中添加信息
        paymentService.savePaymentInfo(orderInfo, PaymentTypeEnum.WEIXIN.getStatus());
        //3.设置参数，调用微信生成二维码的接口
        //把参数转换成xml格式，使用商户的key进行加密
        Map paramMap = new HashMap();
        paramMap.put("appid", weixinPayProperties.getAppid()); //商户id
        paramMap.put("mch_id", weixinPayProperties.getPartner());  //商户号
        paramMap.put("nonce_str", WXPayUtil.generateNonceStr());  //生成唯一随机的一个字符串
        String body = orderInfo.getReserveDate() + "就诊"+ orderInfo.getDepname();  //主体信息
        paramMap.put("body", body); //支付显示的主体信息
        paramMap.put("out_trade_no", orderInfo.getOutTradeNo());  //订单编号
        //paramMap.put("total_fee", order.getAmount().multiply(new BigDecimal("100")).longValue()+"");
        paramMap.put("total_fee", "1");  //订单金额，为了测试，统一写成这个值
        paramMap.put("spbill_create_ip", "127.0.0.1");  //当前地址
        paramMap.put("notify_url", "http://guli.shop/api/order/weixinPay/weixinNotify");  //回调地址
        paramMap.put("trade_type", "NATIVE");  //支付方式：扫码支付
        //4.调用微信生成二维码接口，httpclient调用
        HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
        //设置map参数
        try {
            //先把它转成XML，如何再进行加密
            client.setXmlParam(WXPayUtil.generateSignedXml(paramMap,weixinPayProperties.getPartnerkey()));
            client.setHttps(true);
            client.post(); //完成发送

            //5.返回相关数据
            String xml = client.getContent();
            //转换成map集合
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);
            System.out.println(resultMap);
            //4、封装返回结果集
            Map map = new HashMap<>();
            map.put("orderId", orderId);
            map.put("totalFee", orderInfo.getAmount());
            map.put("resultCode", resultMap.get("result_code"));
            map.put("codeUrl", resultMap.get("code_url"));  //二维码地址

            if(null != resultMap.get("result_code")) {
                //微信支付二维码2小时过期，可采取2小时未支付取消订单
                redisTemplate.opsForValue().set(orderId.toString(), map, 120, TimeUnit.MINUTES);
            }
            return map;

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }


    }

    //调用微信的接口实现支付状态的查询
    @Override
    public Map<String, String> queryPayStatus(Long orderId){
        //1.根据orderId获得订单的信息
        OrderInfo orderInfo = orderService.getById(orderId);

        //2.封装提交参数
        Map paramMap = new HashMap();
        paramMap.put("appid", weixinPayProperties.getAppid());
        paramMap.put("mch_id", weixinPayProperties.getPartner());
        paramMap.put("out_trade_no", orderInfo.getOutTradeNo());  //订单编号
        paramMap.put("nonce_str", WXPayUtil.generateNonceStr());

        //3.设置请求内容
        HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
        try {
            client.setXmlParam(WXPayUtil.generateSignedXml(paramMap,weixinPayProperties.getPartnerkey()));
            client.setHttps(true);
            client.post();

            //4.得到微信接口返回的数据 XML->Map
            String xml = client.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);
            System.out.println("支付状态resultMap："+resultMap);

            return resultMap;
        } catch (Exception e) {
            e.printStackTrace();
            //5.把接口数据返回
            return null;
        }

    }

    //微信退款操作
    @Override
    public Boolean refund(Long orderId) {
        try {
            //获取支付记录信息
            PaymentInfo paymentInfoQuery = paymentService.getPaymentInfo(orderId, PaymentTypeEnum.WEIXIN.getStatus());

            //先添加信息到退款的记录表中
            RefundInfo refundInfo = refundService.saveRefundInfo(paymentInfoQuery);

            //判断当前订单的数据是否已经退款
            if(refundInfo.getRefundStatus().intValue() == RefundStatusEnum.REFUND.getStatus().intValue()) {
                return true;
            }

            //封装微信需要参数
            Map<String,String> paramMap = new HashMap<>(8);
            paramMap.put("appid",weixinPayProperties.getAppid());       //公众账号ID
            paramMap.put("mch_id",weixinPayProperties.getPartner());   //商户编号
            paramMap.put("nonce_str",WXPayUtil.generateNonceStr());  //随机生成的唯一的字符串
            paramMap.put("transaction_id",paymentInfoQuery.getTradeNo()); //微信订单号
            paramMap.put("out_trade_no",paymentInfoQuery.getOutTradeNo()); //商户订单编号
            paramMap.put("out_refund_no","tk"+paymentInfoQuery.getOutTradeNo()); //商户退款单号==》tk+商家订单编号
//       paramMap.put("total_fee",paymentInfoQuery.getTotalAmount().multiply(new BigDecimal("100")).longValue()+"");
//       paramMap.put("refund_fee",paymentInfoQuery.getTotalAmount().multiply(new BigDecimal("100")).longValue()+"");
            paramMap.put("total_fee","1");
            paramMap.put("refund_fee","1");
            //map参数装xml
            String paramXml = WXPayUtil.generateSignedXml(paramMap,weixinPayProperties.getPartnerkey());
            //接口部分
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/secapi/pay/refund");
            client.setXmlParam(paramXml);
            client.setHttps(true);
            //设置证书
            client.setCert(true);
            client.setCertPassword(weixinPayProperties.getPartner());
            client.post();

            //3、接收到返回的第三方的数据
            String xml = client.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);

            //退款成功
            if (null != resultMap && WXPayConstants.SUCCESS.equalsIgnoreCase(resultMap.get("result_code"))) {
                refundInfo.setCallbackTime(new Date());
                refundInfo.setTradeNo(resultMap.get("refund_id"));
                refundInfo.setRefundStatus(RefundStatusEnum.REFUND.getStatus());  //已经退款
                refundInfo.setCallbackContent(JSONObject.toJSONString(resultMap));
                refundService.updateById(refundInfo);
                return true;
            }
            return false;
        }  catch (Exception e) {
            e.printStackTrace();
            return false;
        }

    }
}
